<template>
	<view class="container">
		<view v-if="!download" class="batch-Save">
			<text @click="batchSave">全部选择</text>
		</view>
		<view v-if="download" class="batch-Save">
			<text v-if="!showAction" @click="batchSave">全部选择</text>
		</view>
		<u-grid :col="3" :border="true" class="content-view">
			<u-grid-item v-for="(item, index) in list" :key="index" @click="itemClick(item, index)" class="item"
				:customStyle="style">
				<u-image :width="width+'px'" :height="width+'px'" :src="item.resURL"></u-image>
				<u-checkbox v-show="!showAction"  shape="circle" class="checkbox" v-model="item.check"></u-checkbox >
			</u-grid-item>
		</u-grid>
	
		<view class="action-view" v-if="typeValue">
			<view v-if="downloadShow" class="left-active">
				<text v-if="download" @click="downloadClick">保存</text>
				
				<view v-else class="download-Action">
					<text @click="downloadCanceClick">取消</text>

					<text @click="downloadList">下载</text>
			
				</view>
			</view>
			<view v-if="download" class="show-Action">
				<text v-if="showAction" @click="addClick">添加</text>
				<text v-else @click="cancelClick">取消</text>
				
				<text v-if="showAction" @click="editClick">编辑</text>
				<text v-else @click="delClick">删除</text>	
			</view>
		
		</view>
	
		<view v-if="!typeValue"  class="action-view">
			<view class="show-Action">
				<text  @click="verifyClick">确认</text>
			</view>
		</view>
		<u-popup v-model="showPopup" mode="bottom" border-radius="14">
			<view class="button-box">
				<u-button type="warning" @click="showModal">打开授权设置</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Fab from '@/components/fab.vue'
	import { uploadAlbumPhoto, getAlbumPhoto, delAlbumPhoto, updateAlbum } from '@/api/album.js'
	import { http } from '@/api/service.js'
	import pageMixin from '@/mixins/page.js'
	export default {
		mixins: [pageMixin],
		components: {
			Fab
		},
		data() {
			return {
				showAction: true,
				showPopup:false,
				download:true,
				downloadShow:true,
				content: [{
						text: '删除'
					},
					{
						text: '添加'
					},
				],
				
				style: {
					'padding': '0 0',
					'border-width': '50px',
					'border': '5 solid #007AFF'
				},
				typeValue:true,
				width: 0,
			}
		},
		onLoad(options) {
			console.log(options);
			this.albumId = options.albumId;
			this.init();
			this.getList(this.page)
			if(options.type) {
				this.download = false
				this.typeValue = false
				this.showAction = false
			}
		},
		methods: {
			verifyClick() {
				const list = this.list.filter(item => item.check) // 过滤出 check 为 true 的项
  .map(item => item.resURL); // 提取 resURL 字段
				uni.$emit('imgFLag',{data:list.join('|')}); 
				uni.navigateBack({ delta: 1})
			},
			refresh() {
				this.page = -1;
				this.getList(this.page)
			},
			
			init() {
				let that = this;
				uni.getSystemInfo({
					success(res) {
						that.width = res.windowWidth/3;
					}
				})
			},
			itemClick(item, index) {
				if (!this.showAction) {
					item.check = !item.check;
					this.list.splice(index, 1, item);
				} else {
					// const urls = [item.resURL];
					let arr = this.list.map((item) => {
						return item.resURL
					})
					
					// const urls = [item.resURL];
					uni.previewImage({
						current: index,
						urls: arr,
					});
					// uni.previewImage({
					// 	urls: urls,
					// });
				}
			},
			addClick() {
				let that = this;
				uni.chooseImage({
				    count: 50, //默认9
				    sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['album'], //从相册选择
				    success: function (chooseImageRes) {
						that.upload(chooseImageRes.tempFilePaths, 0);
				    }
				});
			},
			editClick() {
				this.showAction = false;
				this.downloadShow = false;
			},
			
			delClick() {
				this.showAction = true;
				let photoIds = '';
				for (let index = this.list.length - 1; index >= 0; index--) {
					let item = this.list[index];
					if (item.check) {
						photoIds += `,${item.id}`;
					}
				}
				if (photoIds.length > 0) {
					this.delPhoto(this.albumId, photoIds.substring(1))
				}
			},
			
			cancelClick() {
				this.showAction = true;
				this.downloadShow = true;
				this.canceCheckBox()
			},
			
			canceCheckBox() {
				this.list.map(val => {
					val.check = false;
				})
			},
			
			upload(files, index) {
				console.log(files);
				console.log(index);
				if (index === files.length) {
					uni.hideLoading();
					return
				}
				
				const params = {
					albumId: this.albumId
				}
				uni.showLoading({
					title: `正在上传${index + 1}/${files.length}`,
					mask: true
				})
				uploadAlbumPhoto(params, files[index]).then(res => {
					uni.hideLoading();
					console.log(res);
					this.upload(files, index + 1);
					this.$u.toast('上传成功');
					// if (index === files.length - 1) {
					// 	this.page = -1;
					// 	this.getList(this.page)
					// }
					
					this.list = [ res.data[0], ...this.list ]
					// this.list = this.list.concat(res.data);
					this.setAlbumCover(res.data[0].resURL);
				})
			},
			
			getList(page) {
				const params = {
					albumId: this.albumId,
					pageNum: page + 1,
					pageSize: 18,
				}
				getAlbumPhoto(params).then(res => {
					console.log(res);
					this.setData(res);
				})
			},
			
			delPhoto(albumId, photoIds) {
				
				delAlbumPhoto(albumId, photoIds).then(res => {
					console.log(res);
					this.$u.toast('删除成功');
					this.refresh();
				})
			},
			
			setAlbumCover(cover) {
				updateAlbum(this.albumId, cover).then(res => {
					console.log(res);
				})
			},
			
			onReachBottom() {
				this.loadMore();
			},
			
			downloadClick() {
				this.download = false;
				this.showAction = false
			},
			downloadCanceClick() {
				this.download = true;
				this.showAction = true
				this.canceCheckBox()
			},
			downloadList() {
				const res = this.list.filter(val => {
					return val.check
				})
				if(!res.length) return (uni.showToast({
                    title: '请选择图片',
                    icon: 'none'
                 }))
				 this.savePoster(res)

			},
			savePoster(value) {
				let that = this
				uni.getSetting({ //获取用户的当前设置
					success: (res) => {
						if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
							this.saveImageToPhotosAlbum(value);
						} else {
							uni.authorize({ //如果没有授权，向用户发起请求
								scope: 'scope.writePhotosAlbum',
								success: () => {
									this.saveImageToPhotosAlbum(value);
								},
								fail: () => {
									uni.showToast({
										title: "请打开保存相册权限",
										icon: "none",
										duration: 3000
									});
									
									setTimeout(() => {
										that.showPopup = true
									},2000)
								}
							})
						}
					}
				})
			},
			
			saveImageToPhotosAlbum(res) {
				let that = this
				for (let i = 0; i < res.length; i++) {
				uni.downloadFile({
									url: res[i].resURL,
										success: (res) => {
										if (res.statusCode === 200) {
										uni.saveImageToPhotosAlbum({
				                    filePath: res
				                        .tempFilePath, // 图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
				                    success(res) {
				                        uni.showToast({
				                            title: '保存成功',
											icon: 'success',
											duration: 2000
				                        })
										that.downloadCanceClick()
				                        // 如果保存成功需要打开查看，请使用以下方法，同时也支持打开文件
											uni.openDocument({
											  filePath: res.tempFilePath,
											  showMenu: true,
											  success: function (res) {
												console.log('打开文档成功');
											  }
											});
				                    },
				                    fail(err) {
				                        uni.showToast({
				                            title: '图片保存失败',
				                            icon: 'none'
				                        })
				                    }
				                })
												            }
												        }
												    });
				}

			},
			showModal() {
				uni.openSetting({
				        success: function (res) {
				          console.log('打开设置成功', res.authSetting);
				        },
				        fail: function (err) {
				          console.error('打开设置失败', err);
				        }
				});
			},
			batchSave() {
			  this.list.forEach((val, index) => {
					this.$set(this.list, index, { ...val, check: true });
				});
			}
		}
	}
</script>

<style lang="scss">
	.container{

	}
	
	.batch-Save{
		padding: 15rpx 0;
		text-align: right;
	}

	.content-view{
		margin-bottom: 100rpx;
	}
	
	.action-view{
		position: fixed;
		height: 100rpx;
		background-color: #FFFFFF;
		bottom: 0;
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding-left: 30rpx;
		padding-right: 30rpx;
		
		box-shadow: 0px -1px 10px 0px rgba(138, 138, 138, 0.2);
	}
	
	.show-Action {
		flex: 1;
		display: flex;
		justify-content: space-between;
	}
	.left-active{
		flex: 1;
	}
	.download-Action {
		display: flex;
		justify-content: space-between;
	}

	.item{
		background-color: #007AFF;
		.checkbox{
			position: absolute;
			bottom: 30rpx;
			right: 0;
		}
	}
	
	.fix-view{
		position: absolute;
		bottom: 180rpx;
		width: 100%;
	}
	
	.button-box{
		padding: 60rpx;
	}
	

</style>
